import {Image, StyleSheet, View, Text, TouchableOpacity, Platform, KeyboardAvoidingView} from 'react-native';
import {router, Stack, useLocalSearchParams, useRouter} from "expo-router";
import { scaleSize } from "@/utils/screenSize"
import AntDesign from '@expo/vector-icons/AntDesign';
import { Ionicons } from '@expo/vector-icons';
import {useCallback, useEffect, useState} from "react";
import shareIcon from "@/assets/images/releaseImg/shareIcon.png"
import {useSafeAreaInsets} from "react-native-safe-area-context";
import {ImageBackground} from "expo-image";
import bg from "@/assets/demoImg/demo2.png"
import avator from "@/assets/images/me/avator.png"
import GroupTagName from "@/assets/images/releaseImg/groupTagName.png"
import chatIcon from "@/assets/images/releaseImg/chatIcon.png";
import GroupTagScrollView from "@/components/GroupTagScrollView";
import * as React from "react";
import { GestureHandlerRootView } from 'react-native-gesture-handler';
import { TabView, SceneMap } from 'react-native-tab-view';
import Intro from "@/components/GroupTabItem/intro";
import Activity from "@/components/GroupTabItem/activity";
import Member from "@/components/GroupTabItem/member"
import ResoureMessage from '@/components/GroupTabItem/resoureMessage';
import SuperGroup from "@/components/GroupTabItem/superGroup";
import Comment from "@/components/GroupTabItem/comment";
import GroupProfileCard from "@/components/GroupProfileCard";
import resouceIcon from "@/assets/images/releaseImg/resouceIcon.png"
import Share from "@/components/Share"
import {useActionSheet} from "@expo/react-native-action-sheet";
import {GroupVerifty} from "@/types/chat";
import PupoModal from "@/components/pupoModal";
import {getGroupDetailByRequest, getGroupMemberListByRequest, getCardInfoByRequest} from "@/services/registerCommumity";
import {useFocusEffect} from "@react-navigation/native";
import {useConversationStore} from "@/hooks/im/conversation";
import OpenIMSDKRN from "open-im-sdk-rn"
import { v4 as uuidv4 } from "uuid";
import {getToken} from "@/utils";
import {setRegisterGroupData} from "@/store/slices/registerGroupSlice";
import {useDispatch} from "react-redux";
import {setInputDataByItem} from "@/store/slices/createActiveSilce";
import {Resources} from "@expo/config-plugins/build/android";

export default function groupDetailScreen() {

    const tags2 = ['简介','活动','成员', '留言墙', '超级群', '资源消息墙'];

    const tags1 = ['简介','活动','成员'];

    const options = ['成员管理', '编辑社群', '解散社群', '取消'];

    const router = useRouter();
    const [isApply, setIsApply] = useState(false);
    const insets = useSafeAreaInsets();
    const [headerTag, setHeaderTag] = useState(tags2);
    const [tagActive, setTagActive] = useState(0);
    const [showShare, setShowShare] = useState(false);
    const [dissolveModal, setDissolveModal] = useState(false);
    const [detail, setDetail] = useState({});
    const [memberList, setMemberList] = useState([]);
    const [showMemberCard, setShowMemberCard] = useState(false);
    const [memberInfo, setMemberInfo] = useState({});
    const [routes, setRoutes] = React.useState([]);
    const [isLogin, setIsLogin] = useState(false);

    const updateCurrentConversation = useConversationStore((state) => state.updateCurrentConversation);

    const { showActionSheetWithOptions } = useActionSheet();
    const routerParms = useLocalSearchParams();

    const dispatch = useDispatch();



    const checkHasTokenStatus = async () => {
        const token = await getToken();
        console.log('token', token);
        if (token) {
            setIsLogin(true);
        } else {
            setIsLogin(false);
        }
    };

    useEffect(() => {
        console.log('routerParms.groupId', routerParms.groupId);
        console.log('isApply', isApply);
        if (isApply) {
            setHeaderTag(tags2)
        } else {
            setHeaderTag(tags1)
        };

        const routesList = !isApply ? [
            { key: 'Intro', title: 'Tab 1' },
            { key: 'Activity', title: 'Tab 2' },
            { key: 'Member', title: 'Tab 3' },
        ] : [
            { key: 'Intro', title: 'Tab 1' },
            { key: 'Activity', title: 'Tab 2' },
            { key: 'Member', title: 'Tab 3' },
            // { key: 'Comment', title: 'Tab 1' },
            // { key: 'SuperGroup', title: 'Tab 2' },
            // { key: 'ResoureMessage', title: 'Tab 3' },
        ];

        setRoutes(routesList);

    }, [isApply]);


    const getDetail = function () {
        getGroupDetailByRequest({ communityId: routerParms.groupId })
            .then(res => {
                if (res.data.relationship == 1 || res.data.relationship == 2) {
                    setIsApply(false);
                } else if (res.data.relationship > 2 && res.data.relationship <= 4) {
                    setIsApply(true);
                };
                setDetail(res?.data);
                console.log('getGroupDetailByRequest', res)
            })
            .catch(err => {
                console.log('err', err);
            })
    };

    const getMemberList = function () {
        getGroupMemberListByRequest({ communityId: routerParms.groupId })
            .then(res => {
                setMemberList(res?.data?.communityUsers || [])
                console.log('resresresres', res);
            })
            .catch(err => {
                console.log('err', err);
            })
    };

    useFocusEffect(
        useCallback(() => {
            getDetail();
            getMemberList();
            checkHasTokenStatus();
            return () => console.log("Tab unfocused");
        }, [])
    );

    useEffect(() => {
        checkHasTokenStatus();
    }, [])

    const handleTagPress = (index: number) => {
        setTagActive(index);
    };

    const back = function () {
        router.back();
    };

    const goCreateSuperGroup = function () {
        router.push("/registerGroup/createSuperGroup")
    };

    const showCardModal = function (uid, mid, isMe) {
        console.log('uid', uid);
        console.log('mid', mid);
        console.log('hello')
        if (!isMe) {

            const data = {
                communityId: mid,
                memberId: uid,
            };
            getCardInfoByRequest(data)
                .then(res => {
                    setMemberInfo(res.data);
                    setTimeout(() => {
                        setShowMemberCard(true)
                    }, 500);
                    // setShowMemberCard(true);
                    console.log('res', res);
                })
                .catch(err => {
                    console.log('err', err);
                })
        };

    };


    const hideCardModal = function () {
        setShowMemberCard(false);
    };

    const render1 = {
        Intro: () => <Intro detail={detail} />,
        Activity: () => <Activity detail={detail} />,
        Member: () => <Member list={memberList} isApply={isApply} communityId={routerParms.groupId} show={showCardModal} hide={hideCardModal}/>,
    };

    const render2 = {
        Intro: () => <Intro detail={detail} />,
        Activity: () => <Activity detail={detail} />,
        Member: () => <Member list={memberList} isApply={isApply} communityId={routerParms.groupId} show={showCardModal} hide={hideCardModal}/>,
        // Comment: () => <Comment/>,
        // SuperGroup: () => <SuperGroup/>,
        // ResoureMessage: () => <ResoureMessage/>
    };

    const openActionSheet = () => {

        const cancelButtonIndex = 3;

        showActionSheetWithOptions(
            {
                options,
                cancelButtonIndex,
            },
            (buttonIndex) => {
                switch (buttonIndex) {
                    case 0:
                        console.log('成员管理');
                        router.push(`/registerGroup/memberAdmin/${routerParms.groupId}`)
                        break;
                    case 1:
                        console.log('编辑社群');
                        router.push("/registerGroup/")
                        break;
                    case 2:
                        setDissolveModal(true)
                        console.log('解散社群');
                        break;
                    case 3:
                        console.log('取消 selected');
                        break;
                    default:
                        break;
                }
            }
        );
    };

    // const renderSceneList =  !isApply ?  { ...render1 } : { ...render2 }

    const renderScene = SceneMap({ ...render1 });
    const renderScene1 = SceneMap({ ...render2 });

    const handleTabPress = function (index) {
        setTagActive(index);
    };

    const closeShareModal = function () {
        setShowShare(false)
    };

    const goPubileNew = function () {
        router.push("/registerGroup/pubileNew")
    };

    const goJoin = function () {
        router.push(`/registerGroup/applyJoinGroup/${routerParms.groupId}`)
    };

    const goCreateGroup = function () {
        console.log('detaildetail', detail);
        dispatch(setInputDataByItem({ parentId: { parentId: detail?.communityId, index: 0, title: detail?.name } }));

        router.push("/createActivity")
    };

    const goChat = function () {
        console.log('routerParms?.groupId', routerParms?.groupId)
        OpenIMSDKRN.getOneConversation({
            sessionType: 3,
            sourceID: routerParms?.groupId + "",
        }, uuidv4())
            .then(res => {
                console.log('coversaconcoversacon', res)
                updateCurrentConversation(res);
                router.push(`/chat/${routerParms?.groupId}`)
            })
            .catch(err => {
                console.log('err', err);
            })

    };

    const goJoinApply = function () {
        console.log('routerParms.groupIdssss', routerParms.groupId);
        console.log('isLoginsssss', isLogin);
        if (isLogin) {
            console.log('e')
            router.push(`/registerGroup/applyJoinGroup/${routerParms.groupId}`)
        } else {
            router.push(`/login`)
        };

    };

    const showCard = function () {
        setShowMemberCard(true);
    };

    const hideCard = function () {
        setShowMemberCard(false);
    };


    return (
        <KeyboardAvoidingView
            behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
            keyboardVerticalOffset={Platform.OS === 'ios' ? 0 : 0} // 可根据需求调整
            style={{ flex: 1, backgroundColor: "#F7F7F7" }}
        >
        <View style={{ height: "100%", backgroundColor: "#F7F7F7" }}>
            <Stack.Screen
                options={{
                    headerShown: false,
                }}
            />
            <ImageBackground source={{ uri: detail?.coverUrl }} style={{ position: "relative" }}>
                <View style={{ width: '100%', height: "100%", position: "absolute", backgroundColor: "rgba(0,0,0,.3)" }}></View>
                <View style={{ paddingLeft: 7, paddingRight: 21, paddingBottom: 16}}>
                    <View style={[styles.flexHeader, { paddingTop: insets.top, }]}>
                        <TouchableOpacity onPress={back}>
                            <View>
                                <AntDesign name="left" size={19} color="#FFF" />
                            </View>
                        </TouchableOpacity>

                        <View style={styles.headerTitle}>
                            <Text style={styles.headerTitleText}>社群详情</Text>
                        </View>
                        <TouchableOpacity onPress={() => setShowShare(true)}>
                            <View style={styles.shareIcon}>
                                <Image source={shareIcon} style={{ width: "100%", height: "100%" }} />
                            </View>
                        </TouchableOpacity>
                    </View>
                    <View style={styles.headerInfoWrap}>
                        <View style={styles.avator}>
                            <Image source={{ uri: detail?.coverUrl }} style={{ width: "100%", height: "100%" }}/>
                        </View>
                        <View style={styles.headerGroupNameWrap}>
                            <View style={styles.headerName}>
                                <Text style={styles.headerNameText}>{detail?.name}</Text>
                            </View>
                            <View style={{ flexDirection: 'row' }}>
                                {
                                    detail?.tags?.map((item: any, index: number) => {
                                        return (
                                            <ImageBackground source={GroupTagName} style={[styles.tagWrap, { marginRight: 5, }]} key={index}>
                                                <Text style={styles.tagWrapText}>{ item}</Text>
                                            </ImageBackground>
                                        )
                                    })
                                }
                            </View>


                        </View>
                    </View>
                    {/*<View style={styles.content}>*/}
                    {/*    <Text style={styles.contentText}>*/}
                    {/*        { detail?.founderIntroduce }*/}
                    {/*    </Text>*/}
                    {/*</View>*/}
                    <View style={styles.noticeContainer}>
                        <View style={styles.noticeTitle}>
                            <Text style={styles.noticeTitleText}>群公告</Text>
                        </View>
                        <View style={styles.noticeContent}>
                            <Text style={styles.noticeContentText}>{ detail?.announcement }</Text>
                        </View>
                    </View>
                </View>

            </ImageBackground>


            {
                !isApply && (
                    <View style={styles.groupListContainer}>
                        <View style={[styles.body, { backgroundColor: tagActive == 0 ? "#fff" : "#F9F9F9"  }]}>
                            <View style={styles.bodyHeaderList}>
                                <GestureHandlerRootView>
                                    <GroupTagScrollView
                                        tags={tags1}
                                        onTagPress={handleTagPress}
                                        activeIndex={tagActive}
                                    />
                                </GestureHandlerRootView>
                            </View>
                            <GestureHandlerRootView style={{ flex: 1 }}>
                                <TabView
                                    navigationState={{ index: tagActive, routes }}
                                    renderScene={renderScene}
                                    onIndexChange={handleTabPress}
                                    renderTabBar={() => null}
                                />
                            </GestureHandlerRootView>
                        </View>
                    </View>
                )
            }
            {
                isApply && (
                    <View style={styles.groupListContainer}>
                        <View style={[styles.body, { backgroundColor: tagActive == 0 ? "#fff" : "#F9F9F9"  }]}>
                            <View style={styles.bodyHeaderList}>
                                <GestureHandlerRootView>
                                    <GroupTagScrollView
                                        tags={tags1}
                                        onTagPress={handleTagPress}
                                        activeIndex={tagActive}
                                    />
                                </GestureHandlerRootView>
                            </View>
                            <GestureHandlerRootView style={{ flex: 1 }}>
                                <TabView
                                    navigationState={{ index: tagActive, routes }}
                                    renderScene={renderScene1}
                                    onIndexChange={handleTabPress}
                                    renderTabBar={() => null}
                                />
                            </GestureHandlerRootView>
                        </View>
                    </View>
                )
            }
            {
                isApply && tagActive == 0 && (
                    <View style={styles.footer}>
                        <TouchableOpacity onPress={goChat} style={styles.footerLeft}>
                           <View style={{ width: 50 }}>
                               <View style={styles.footerLeftIcon}>
                                   <Image source={chatIcon} style={{ width: "100%", height: "100%" }} />
                               </View>
                               <View style={styles.footerLeftTitle}>
                                   <Text style={styles.footerLeftTitleText}>进入聊天</Text>
                               </View>
                           </View>
                        </TouchableOpacity>
                        {
                            detail?.role >= 3 && (
                                <>
                                    <TouchableOpacity onPress={goCreateGroup}>
                                        <View style={styles.buildActivity}>
                                            <Text style={styles.buildActivityText}>发布活动</Text>
                                        </View>
                                    </TouchableOpacity>
                                    <TouchableOpacity onPress={openActionSheet}>
                                        <View style={styles.adminBtn}>
                                            <Text style={styles.adminBtnText}>管理</Text>
                                        </View>
                                    </TouchableOpacity>
                                </>

                            )
                        }

                    </View>
                )
            }

            {
                !isApply && (detail?.relationship == 1 || detail?.relationship == 5) && (
                    <TouchableOpacity  activeOpacity={1}>
                        <View style={[styles.footer, { marginRight: 12}]} >
                            <View style={{ flex: 1 }}></View>
                            <TouchableOpacity onPress={goJoinApply}>
                                <View style={styles.adminBtn}>
                                    <Text style={styles.adminBtnText}>加入</Text>
                                </View>
                            </TouchableOpacity>
                        </View>
                    </TouchableOpacity>
                )
            }

            {
                !isApply && detail?.relationship == 2 && (
                    <View style={[styles.footer, { paddingRight: 12}]}>
                        <View style={{ flex: 1 }}></View>
                        <TouchableOpacity activeOpacity={1}>
                            <View style={styles.examine}>
                                <Text style={styles.examineText}>审核中</Text>
                            </View>
                        </TouchableOpacity>
                    </View>
                )
            }
            <GroupProfileCard visible={showMemberCard} show={showCardModal} hide={hideCardModal} data={memberInfo}/>
            {
                tagActive === 5 && (
                    <TouchableOpacity onPress={goPubileNew}>
                        <View style={styles.resourceFlxIcon}>
                            <Image source={resouceIcon} style={{ width: "100%", height: "100%" }} />
                        </View>
                    </TouchableOpacity>
                )
            }

            {
                tagActive === 4 && (
                    <TouchableOpacity onPress={goCreateSuperGroup}>
                        <View style={[styles.superGroupContainer, { transform: [{ translateX: -50 }] }]}>
                            <Text style={styles.superGroupText}>
                                创建超级群</Text>
                            <AntDesign name="right" size={12} color="#fff" />
                        </View>
                    </TouchableOpacity>
                )
            }
            <Share
                visible={showShare}
                close={closeShareModal}
            />
            <PupoModal
                title={"解散社群"}
                visible={dissolveModal}
                onOk={() => setDissolveModal(false)}
                okCancel={() => setDissolveModal(false)}
            >
                <View style={styles.dissolveGroup}>
                    <Text style={styles.dissolveGroupText}>解散该社群</Text>
                </View>
            </PupoModal>

        </View>
        </KeyboardAvoidingView>
    );
}

const styles = StyleSheet.create({
    shareIcon: {
        width: 21,
        height: 21,
    },
    flexHeader: {
        flexDirection: "row",
    },
    headerTitle: {
        flex: 1,
        textAlign: "center",
    },
    headerTitleText: {
        textAlign: "center",
        color: "#FFF",
        fontSize: 16,
    },
    avator: {
        width: 54,
        height: 54,
        borderRadius: 50,
        overflow: "hidden"
    },
    headerInfoWrap: {
        flexDirection: "row",
        alignItems: "center",
        marginTop: 22,
    },
    headerGroupNameWrap: {
      marginLeft: 11,
    },
    headerName: {},
    headerNameText: {
        fontSize: 18,
        color: "#fff",
    },
    tagWrap: {
        width: 42,
        height: 16,
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "center",
        marginTop: 6,
    },
    tagWrapText: {
        fontSize: 10,
        color: "#fff",
    },
    content: {
        marginTop: 10,
    },
    contentText: {
        fontSize: 10,
        color: "#fff",
    },
    noticeContainer: {
        backgroundColor: "rgba(255,255,255,0.1)",
        paddingHorizontal: 9,
        paddingVertical: 10,
        borderRadius: 8,
        marginTop: 12,
        marginBottom: 15,
    },
    noticeTitle: {

    },
    noticeTitleText: {
        color: "#fff",
        fontSize: 12,
    },
    noticeContent: {
        marginTop: 4,
    },
    noticeContentText: {
        color: "#fff",
        fontSize: 12,
    },
    groupListContainer: {
        flex: 1,
    },
    footer: {
        flexDirection: "row",
        paddingBottom: 29,
        paddingLeft: 24,
        backgroundColor: "#fff",
        paddingTop: 12,
    },
    footerLeft: {
        flex: 1,
    },
    footerLeftIcon: {
        width: 20,
        height: 20,
        margin: "auto",
    },
    footerLeftTitle: {
        width: "100%",
        marginTop: 4,
    },
    footerLeftTitleText: {
        fontSize: 10,
        color: "#2A2B30",
        textAlign: "center",
    },
    buildActivity: {
        width: 110,
        height: 40,
        borderRadius: 20,
        borderColor: "#EC6138",
        borderWidth: 1,
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center",
        marginLeft: 79,
        marginRight: 12,
    },
    buildActivityText: {
        color: "#EC6138"
    },
    adminBtn: {
        backgroundColor: "#EC6138",
        width: 110,
        height: 40,
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center",
        borderRadius: 20,
        marginRight: 12,
    },
    adminBtnText: {
        color: "#fff",
    },
    body: {
        flex: 1,
        marginTop: -10,
        // backgroundColor: "#F9F9F9",
        borderTopLeftRadius: 8,
        borderTopRightRadius: 8,
    },
    bodyHeaderList: {
        flexDirection: "row",
        paddingTop: 8,
        width: "100%",
    },
    headerItem: {
        paddingVertical: 5,
        paddingHorizontal: 5,
        flexDirection: "row",
        justifyContent: "center",
        alignItems: 'center',
        backgroundColor: "red",
        marginHorizontal: 5,
    },
    examine:{
        backgroundColor: "#E4E6EC",
        width: 110,
        height: 40,
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center",
        borderRadius: 20,
    },
    examineText: {
        color: "#fff",
    },
    resourceFlxIcon: {
        position: "absolute",
        bottom: 60,
        right: 20,
        width: 68,
        height: 68,
    },
    superGroupContainer: {
        position: "absolute",
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "center",
        bottom: 50,
        left: "50%",
        width: 120,
        height: 34,
        backgroundColor: "#EC6138",
        borderRadius: 20,
        shadowColor: 'rgba(236,97,56,1)',
        shadowOffset: { width: 0, height: 2 },
        shadowOpacity: 0.4,
        shadowRadius: 10,
        // Android上的阴影
        elevation: 10,
    },
    superGroupText: {
        color: "#fff",
        fontSize: 14,
    },
    dissolveGroup: {
        flexDirection: "row",
        justifyContent: "center",
        marginTop: 14,
        marginBottom: 34,
    },
    dissolveGroupText: {
        fontSize: 16,
        color: "#676978"
    },
});
